/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Proveedores.java
 *
 * Created on 29-nov-2011, 19:08:24
 */
package formularios;

import clases.*;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Elio
 */
public class Proveedores extends javax.swing.JDialog {
    

    /** Creates new form Proveedores */
    public Proveedores() {
        initComponents();
        completartablaproveedores();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        MenuProveedores = new javax.swing.JPopupMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jLayeredPane1 = new javax.swing.JLayeredPane();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaproveedores = new javax.swing.JTable();
        ifAltaProveedores = new javax.swing.JInternalFrame();
        lblAltaProveedores = new javax.swing.JLabel();
        btnGuardarProveedor = new javax.swing.JButton();
        btnCancelarProveedor = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        txtRazonSocial = new javax.swing.JTextField();
        txtCUIT = new javax.swing.JFormattedTextField();
        txtDomicilio = new javax.swing.JTextField();
        txtTelefono = new javax.swing.JTextField();
        txtemail = new javax.swing.JTextField();
        cbTipoProveedor = new javax.swing.JComboBox();
        jPanel2 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        btnNuevoProveedor = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        txtBuscarProveedor = new javax.swing.JTextField();

        jMenuItem1.setText("Modificar Datos");
        jMenuItem1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        MenuProveedores.add(jMenuItem1);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Modulo de Proveedores");
        setIconImages(null);
        setResizable(false);

        jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 18));
        jLabel1.setText("Proveedores");
        jLabel1.setBounds(220, 10, 95, 22);
        jLayeredPane1.add(jLabel1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        tablaproveedores.setAutoCreateRowSorter(true);
        tablaproveedores.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tablaproveedores.setComponentPopupMenu(MenuProveedores);
        tablaproveedores.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaproveedoresMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tablaproveedores);

        jScrollPane1.setBounds(10, 40, 520, 220);
        jLayeredPane1.add(jScrollPane1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        ifAltaProveedores.setClosable(true);
        ifAltaProveedores.setTitle("Alta Proveedores");
        ifAltaProveedores.setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/rolesvarios.png"))); // NOI18N

        lblAltaProveedores.setFont(new java.awt.Font("Tahoma", 1, 12));
        lblAltaProveedores.setText("Alta Proveedores");

        btnGuardarProveedor.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/filesave.png"))); // NOI18N
        btnGuardarProveedor.setText("Guardar");
        btnGuardarProveedor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarProveedorActionPerformed(evt);
            }
        });

        btnCancelarProveedor.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/salir.png"))); // NOI18N
        btnCancelarProveedor.setText("Cancelar");
        btnCancelarProveedor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarProveedorActionPerformed(evt);
            }
        });

        jPanel1.setLayout(new java.awt.GridLayout(6, 0, 5, 5));
        jPanel1.add(txtRazonSocial);

        try {
            txtCUIT.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##-########-#")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jPanel1.add(txtCUIT);
        jPanel1.add(txtDomicilio);
        jPanel1.add(txtTelefono);
        jPanel1.add(txtemail);

        cbTipoProveedor.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Insumos Veterinarios", "Insumos Electronicos", "Animales", "Alimentos" }));
        jPanel1.add(cbTipoProveedor);

        jPanel2.setLayout(new java.awt.GridLayout(6, 0, 5, 5));

        jLabel4.setText("Razón Social");
        jPanel2.add(jLabel4);

        jLabel5.setText("CUIT");
        jPanel2.add(jLabel5);

        jLabel6.setText("Domicilio");
        jPanel2.add(jLabel6);

        jLabel7.setText("Teléfono");
        jPanel2.add(jLabel7);

        jLabel8.setText("Correo Electrónico");
        jPanel2.add(jLabel8);

        jLabel9.setText("Tipo Proveedor");
        jPanel2.add(jLabel9);

        javax.swing.GroupLayout ifAltaProveedoresLayout = new javax.swing.GroupLayout(ifAltaProveedores.getContentPane());
        ifAltaProveedores.getContentPane().setLayout(ifAltaProveedoresLayout);
        ifAltaProveedoresLayout.setHorizontalGroup(
            ifAltaProveedoresLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ifAltaProveedoresLayout.createSequentialGroup()
                .addGroup(ifAltaProveedoresLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(ifAltaProveedoresLayout.createSequentialGroup()
                        .addGap(22, 22, 22)
                        .addGroup(ifAltaProveedoresLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnGuardarProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(34, 34, 34)
                        .addGroup(ifAltaProveedoresLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btnCancelarProveedor)))
                    .addGroup(ifAltaProveedoresLayout.createSequentialGroup()
                        .addGap(132, 132, 132)
                        .addComponent(lblAltaProveedores)))
                .addContainerGap(32, Short.MAX_VALUE))
        );
        ifAltaProveedoresLayout.setVerticalGroup(
            ifAltaProveedoresLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ifAltaProveedoresLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblAltaProveedores)
                .addGap(11, 11, 11)
                .addGroup(ifAltaProveedoresLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 145, Short.MAX_VALUE))
                .addGap(25, 25, 25)
                .addGroup(ifAltaProveedoresLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnGuardarProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnCancelarProveedor, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(72, 72, 72))
        );

        ifAltaProveedores.setBounds(70, 0, 370, 340);
        jLayeredPane1.add(ifAltaProveedores, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jPanel3.setLayout(new java.awt.GridLayout(1, 0));

        btnNuevoProveedor.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconos/Symbol-Add.png"))); // NOI18N
        btnNuevoProveedor.setText("Nuevo Proveedor");
        btnNuevoProveedor.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNuevoProveedorActionPerformed(evt);
            }
        });
        jPanel3.add(btnNuevoProveedor);

        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel2.setText("Buscar Proveedor");
        jPanel3.add(jLabel2);

        txtBuscarProveedor.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtBuscarProveedorKeyReleased(evt);
            }
        });
        jPanel3.add(txtBuscarProveedor);

        jPanel3.setBounds(10, 307, 520, 33);
        jLayeredPane1.add(jPanel3, javax.swing.JLayeredPane.DEFAULT_LAYER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLayeredPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 536, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLayeredPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 373, Short.MAX_VALUE)
                .addContainerGap())
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-552)/2, (screenSize.height-433)/2, 552, 433);
    }// </editor-fold>//GEN-END:initComponents

private void btnCancelarProveedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarProveedorActionPerformed
    
    ifAltaProveedores.setVisible(false);
    limpiarInternalFrame();
    
    
}//GEN-LAST:event_btnCancelarProveedorActionPerformed

private void btnGuardarProveedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarProveedorActionPerformed
   String boton = btnGuardarProveedor.getText();
   
   if (boton.equals("Guardar"))
   {
    altaProveedor();
   
   }
   else  {
       int op = JOptionPane.showConfirmDialog(null,"Esta a punto de modificar los datos del proveedor, una vez modificados no se podra ver la información anterior \n ¿Esta seguro que desea continuar con la modificación de los datos?", "Confirme la modificación",JOptionPane.YES_NO_OPTION);
       if(op == JOptionPane.YES_OPTION)
               modificarProveedor(idproveedor);
       else{
           ifAltaProveedores.setVisible(false);
           limpiarInternalFrame();
       }  
   }
   
    completartablaproveedores();
}//GEN-LAST:event_btnGuardarProveedorActionPerformed

private void btnNuevoProveedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoProveedorActionPerformed

    limpiarInternalFrame();
    ifAltaProveedores.setVisible(true);
    
    
}//GEN-LAST:event_btnNuevoProveedorActionPerformed

private void txtBuscarProveedorKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBuscarProveedorKeyReleased
  String buscar = txtBuscarProveedor.getText();
  
  ResultSet buscando = new abmProveedor().BuscarProveedor(buscar);
   tablaproveedores.setAutoResizeMode(tablaproveedores.AUTO_RESIZE_ALL_COLUMNS);
              
   ConversorRSaDefaultTableModel.completar(buscando, modelo);
  
}//GEN-LAST:event_txtBuscarProveedorKeyReleased

private void tablaproveedoresMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaproveedoresMouseClicked
int fila = tablaproveedores.rowAtPoint(evt.getPoint()); 

         int columna = tablaproveedores.columnAtPoint(evt.getPoint());
         if ((fila > -1) && (columna == 0)){
         proveedor = String.valueOf(modelo.getValueAt(fila,columna)); 
         }
        
   System.out.println(columna);
}//GEN-LAST:event_tablaproveedoresMouseClicked

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
   limpiarInternalFrame();
   ifAltaProveedores.setVisible(true);
   completarDatos(proveedor);
   idproveedor = new abmProveedor().getIdProveedor(proveedor);
  
}//GEN-LAST:event_jMenuItem1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Proveedores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Proveedores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Proveedores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Proveedores.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Proveedores().setVisible(true);
            }
        });
    }
    
    
    
   public void Conectar(){
        try{
            mdbc = new conexion();
            mdbc.init();
            Connection conn= mdbc.getMyConnection();
            stmt = conn.createStatement();
        }catch(Exception ex)
        {
            JOptionPane.showMessageDialog(null, "Problemas al concetarse a la Base de Datos","Error",JOptionPane.ERROR_MESSAGE);
        }
    }
     
    private void completartablaproveedores() {
        String sql = "Select razonsocial as 'Proveedor',  cuit as 'CUIT', domicilio as 'Domicilio', telefono as 'Telefono', email as 'Correo Electrónico'"
                + "     from Proveedor";
                
        try {
            Conectar();
            ResultSet rs = stmt.executeQuery(sql);

      
            tablaproveedores.setModel(modelo);
            tablaproveedores.setAutoResizeMode(tablaproveedores.AUTO_RESIZE_ALL_COLUMNS);
              
                    
            ConversorRSaDefaultTableModel.completar(rs, modelo);

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Error en la consulta de animales", "Error", JOptionPane.ERROR_MESSAGE);
        }
        
    }
    
    
    
    private void altaProveedor() {
      
      String cuit = txtCUIT.getText();
      String nombre = txtRazonSocial.getText();
      String domicilio = txtDomicilio.getText();
      String telef = txtTelefono.getText();
      String mail = txtemail.getText();
      String tipo = String.valueOf(cbTipoProveedor.getItemAt(cbTipoProveedor.getSelectedIndex()));
      
      if(!existeCUIT(cuit)){
          
          new abmProveedor().AltaProveedor(cuit, nombre, domicilio, telef, mail, tipo);
          ifAltaProveedores.setVisible(false);
      }
         
     
    }
    
    private void modificarProveedor(String id){
//      int idprov = Integer.valueOf(id)  ;
      String cuit = txtCUIT.getText();
      String nombre = txtRazonSocial.getText();
      String domicilio = txtDomicilio.getText();
      String telef = txtTelefono.getText();
      String mail = txtemail.getText();
      String tipo = String.valueOf(cbTipoProveedor.getItemAt(cbTipoProveedor.getSelectedIndex()));
      
      new abmProveedor().ModificaProveedor(id, cuit, nombre, domicilio, telef, mail, tipo);
      ifAltaProveedores.setVisible(false);
    }

    private boolean existeCUIT(String cuit) {
    
     abmProveedor abmp = new abmProveedor(); 
     String nombre;
 //    ResultSet rsNombre = abmp.BuscarProveedor(nombre);
     
     try{
     
      ResultSet rsCuit = abmp.buscarCUIT(cuit);
     
     //Verificamos que no exista el proveedor
     if(!rsCuit.first())
     {
     
          return false;
     
     }
        else {
                nombre = rsCuit.getString(1);
                cuit = rsCuit.getString(2);
                
                int op = JOptionPane.showConfirmDialog(null,"El proveedor ya existe \n Nombre:'"+nombre+"'  \n NºCUIT: '"+cuit+"'\n\n ¿Desea modificar los datos de este proveedor?" , "Error: Proveedor existente!! ", JOptionPane.YES_NO_OPTION);
                if(op == JOptionPane.YES_OPTION)
                {
                    ifAltaProveedores.setVisible(false);
                    limpiarInternalFrame();
                    ifAltaProveedores.setVisible(true);
                    completarDatos(nombre);
                    idproveedor = new abmProveedor().getIdProveedor(proveedor);
                    
                    System.out.println(btnGuardarProveedor.getText());
                                        }
                return true;
              
            }     
     } catch (Exception ex) {
                 
                JOptionPane.showMessageDialog(null,"Error en la consulta a la base de Datos ","Error",JOptionPane.ERROR_MESSAGE);
                 return true;
            }
     }

    private void limpiarInternalFrame() {
        txtCUIT.setText("");
        txtDomicilio.setText("");
        txtRazonSocial.setText("");
        txtTelefono.setText("");
        txtemail.setText("");
        lblAltaProveedores.setText("Alta Proveedores");
        btnGuardarProveedor.setText("Guardar");
        
    }
    
    private void completarDatos(String prov){
        lblAltaProveedores.setText("Modificacion de Datos Proveedores");
        btnGuardarProveedor.setText("Modificar");
        try{
            
            ResultSet cd = new abmProveedor().BuscarProveedor(prov);
            if(cd.first()){
                txtRazonSocial.setText(cd.getString("Proveedor"));
                txtCUIT.setText(cd.getString("CUIT"));
//              txtCUIT.setEditable(false);
                txtDomicilio.setText(cd.getString("Domicilio"));
                txtTelefono.setText(cd.getString("Telefono"));
                txtemail.setText(cd.getString("Correo Electrónico"));
            }
            else txtRazonSocial.setText(prov);
        }catch(Exception ex)
        {
            JOptionPane.showMessageDialog(null, "Problemas al conectarse a la Base de Datos","Error",JOptionPane.ERROR_MESSAGE);
        }
    }
 

    private Statement stmt;
    private conexion mdbc;
    DefaultTableModel modelo = new DefaultTableModel();
    String proveedor,idproveedor;
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPopupMenu MenuProveedores;
    private javax.swing.JButton btnCancelarProveedor;
    private javax.swing.JButton btnGuardarProveedor;
    private javax.swing.JButton btnNuevoProveedor;
    private javax.swing.JComboBox cbTipoProveedor;
    private javax.swing.JInternalFrame ifAltaProveedores;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JLayeredPane jLayeredPane1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblAltaProveedores;
    private javax.swing.JTable tablaproveedores;
    private javax.swing.JTextField txtBuscarProveedor;
    private javax.swing.JFormattedTextField txtCUIT;
    private javax.swing.JTextField txtDomicilio;
    private javax.swing.JTextField txtRazonSocial;
    private javax.swing.JTextField txtTelefono;
    private javax.swing.JTextField txtemail;
    // End of variables declaration//GEN-END:variables


    
}



